package UDP.UDP2;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

//客户端
public class UdpEchoClient {
    private DatagramSocket socket;
    private String serverIp;
    private int port;
    public UdpEchoClient(String serverIp, int port) throws SocketException {
        socket = new DatagramSocket();
        this.serverIp = serverIp;
        this.port = port;
    }
    //启动客户端
    public void start() throws IOException {
        Scanner in = new Scanner(System.in);
        while(true) {
            System.out.print("->");
            //1.创造Udp请求,并发送
            String request = in.next();
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),
                    request.getBytes().length, InetAddress.getByName(this.serverIp), this.port);
            socket.send(requestPacket);
            //2.接收服务器响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(responsePacket);
            //3.打印响应
            String response = new String(responsePacket.getData(), 0, responsePacket.getLength());
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("127.0.0.1", 9090);
        client.start();
    }
}
